import React, { useEffect, useRef, useState } from "react";
import { Button, Layout, Popconfirm, Space, Tag, message, notification, theme } from "antd";
import Table, { ColumnsType } from "antd/es/table";
import { DeleteOutlined } from "@ant-design/icons";
import {
  ModalForm,
  ProFormInstance,
  ProFormText,
} from "@ant-design/pro-components";
import { useAppSelector, useAppDispatch } from "../../app/hooks";
import { RootState } from "../../app/store";
import { Add, Delete, Modify, Set } from "../rolemanage/roleSlice";
import axios from "axios";
const { Content } = Layout;
type NotificationType = 'success' | 'info' | 'warning' | 'error';
export interface RoleDataType {
  id: string;
  name: string;
  description: string;
}



const App: React.FC = () => {
  // rowSelection object indicates the need for row selection
  const rowSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: RoleDataType[]) => {
      setSelectedRole(selectedRowKeys.toString())
    },
    getCheckboxProps: (record: RoleDataType) => ({
      disabled: record.name === "Disabled User", // Column configuration not to be checked
      name: record.name,
    }),
  };
  const [isRoleModalOpen, setRoleModalOpenState] = useState(false);
  const [RoleMorA, setRoleMorA] = useState("update");
  const [RoleUpdateMsg, setRoleUpdateMsg] = useState({} as RoleDataType);
  const [selectedRole, setSelectedRole] = useState<string>('');
  const roleList = useAppSelector((state: RootState) => state.role.roleMsg);
  const dispatch = useAppDispatch();
  
  function getRoleTableData() {
    axios.get("/api/role").then((response) => {
      dispatch(Set(response.data.data.result))
    });
  }

  const columns: ColumnsType<RoleDataType> = [
    {
      title: "ID",
      dataIndex: "id",
      key: "id",
      render: (text, record) => <a>{text}</a>,
    },
    {
      title: "角色",
      key: "role",
      dataIndex: "role",
      render: (_, { name }) => (
        <>
          <Tag color={"blue"} key={name}>
            {name}
          </Tag>
        </>
      ),
    },
    {
      title: "描述",
      dataIndex: "description",
      key: "description",
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <a onClick={() => OpenModal(record)}>编辑</a>
          <Popconfirm
            title={<DeleteOutlined />}
            description="你确定要删除这个职位吗?"
            onConfirm={() => confirm(record)}
            onCancel={cancel}
            okText="是"
            cancelText="否"
          >
            <a>删除</a>
          </Popconfirm>
        </Space>
      ),
    },
  ];



  const {
    token: { colorBgContainer },
  } = theme.useToken();

  // 查询
  const [api, contextHolder] = notification.useNotification();

  const openNotificationWithIconUsed = (type: NotificationType, UsedId:string[]) => {
    const usedRole:string[] = []
    roleList.map((role) => {
      if(UsedId.includes(role.id)){
        usedRole.push(role.name)
      }
    })
    console.log(usedRole);
    
    api[type]({
      message: '请注意😬😬😬',
      description:<>      <Tag color="green">{usedRole.toString()}</Tag>被使用不能删除
      </>

    });
  };

  const openNotificationWithIconNo = (type: NotificationType, NoId:string[]) => {
    const noRole:string[] = []
    roleList.map((role) => {
      if(NoId.includes(role.id)){
        noRole.push(role.name)
      }
    })
    api[type]({
      message: '请注意😬😬😬',
      description:<>    <Tag color="green">{noRole.toString()}</Tag> 不存在不能删除
      </>

    });
  };
  const confirm = (record: RoleDataType) => {
    deleteRole(record);
  };

  const cancel = (e: any) => {
    message.error("已取消");
  };

  function deleteRole(record: RoleDataType) {
    axios.delete(`api/role/${record.id}`).then((response) => {
      if (response.data.res === 'NoId') {
        message.error("未找到此职位");
      }else if(response.data.res === 'used'){
        message.error("被使用不能删除")
      } 
      else {
        dispatch(Delete(record.id))
      }
    });
  }

  // ModalForm
  function OpenAddModal() {
    setRoleModalOpenState(true);
    setRoleMorA("add");
  }

  const waitTime = (time: number = 10) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve(true);
      }, time);
    });
  };

  async function UpdateOrAddRole(values: any) {
    await waitTime(1000);
    if (RoleMorA === "add") {
      axios
        .post("/api/role", {
          name: values.name,
          description: values.description,
        })
        .then((response) => {
          if (response.status !== 200) {
            message.error("添加失败");
            return false;
          }
          dispatch(Add({
            id:response.data.id,
            name: values.name,
            description: values.description
          }))
        });
      message.success("添加成功");
      setRoleModalOpenState(false);
      return true;
    } else if (RoleMorA === "update") {
      axios
        .put(`/api/role/${RoleUpdateMsg.id}`, {
          name: values.name,
          description: values.description,
        })
        .then((response) => {
          if (response.status !== 200) {
            message.error("修改失败");
            return false;
          }
          dispatch(Modify({
            id:response.data.id,
            name: values.name,
            description: values.description
          }))
        });
      message.success("修改成功");
      setRoleModalOpenState(false);
      // getRoleTableData();
      return true;
    }
  }

  const confirmDeleteRoleByIds = () => {
    const ids:string[] = selectedRole.split(",")
    if(ids.length>0){
      axios
      .delete("/api/role", {
        params: {
          ids: selectedRole,
        },
      })
      .then((response) => {
        if (response.status !== 200) {
          console.log(response);
          
          message.error("删除失败");
        }else{
          console.log(response.data);
          response.data.delID.map((id: any) => {
            dispatch(Delete(id))
            return id
          })
          if (response.data.usedid.length>0) {
            openNotificationWithIconUsed("error",response.data.usedid)
          }
          if (response.data.noid.length>0) {
            openNotificationWithIconNo('error',response.data.noid)
          }
        }
      });
    }
    else{
      message.error("请至少选择一个角色")
    }

      // getRoleTableData()
  };

  function OpenModal(record: any) {
    setRoleModalOpenState(true);
    setRoleUpdateMsg(record);
    setRoleMorA("update");    
  }

  const restFormRef = useRef<ProFormInstance>();

  // Modal
  const ModalTitle = RoleMorA === "update" ? "修改" : "添加";
  const validateRoleName= async (_: any, value: any) => {
    if (!value) {
      return Promise.reject("请输入名称");
    }
    if (/\s/.test(value)) {
      return Promise.reject("名字不能含空格");
    }
    if (value.replace(/[^\x00-\xff]/g, "aa").length > 12) {
      return Promise.reject("名字太长了");
    }
    return Promise.resolve();
  };
  const validateDescription= async (_: any, value: any) => {
    if (!value) {
      return Promise.reject("请输入一个简短的描述");
    }
    if (/\s/.test(value)) {
      return Promise.reject("描述不能含空格");
    }
    if (value.replace(/[^\x00-\xff]/g, "aa").length > 40) {
      return Promise.reject("描述内容太长了");
    }
    return Promise.resolve();
  };

  useEffect(() => {
    getRoleTableData();
  }, []);

  return (
    <div>
       {contextHolder}
      <Content
        style={{
          margin: "24px 16px",
          padding: 24,
          minHeight: 280,
          background: colorBgContainer,
        }}
      >
        <div>
          <Space direction="horizontal">
            <Button type="primary" size="middle" onClick={OpenAddModal}>
              添加
            </Button>
            <Popconfirm
              title="Delete"
              description="你确定要删除这些职称吗?"
              onConfirm={confirmDeleteRoleByIds}
              onCancel={cancel}
              okText="是"
              cancelText="否"
            >
              <Button danger type="primary" size="middle">
                删除
              </Button>
            </Popconfirm>
          </Space>
          <Table
            rowKey={(record) => {
              return record.id;
            }}
            rowSelection={{
              type: "checkbox",
              ...rowSelection,
            }}
            style={{minWidth:'600px'}}
            columns={columns}
            dataSource={roleList}
            sticky
            pagination={false}
          />
          <div>
            <ModalForm
              title={ModalTitle}
              open={isRoleModalOpen}
              formRef={restFormRef}
              onFinish={UpdateOrAddRole}
              modalProps={{
                destroyOnClose: true,
                onCancel: () => console.log("run"),
              }}
              submitter={{
                searchConfig: {
                  resetText: "重置",
                },
                resetButtonProps: {
                  onClick: () => {
                    restFormRef.current?.resetFields();
                  },
                },
              }}
              onOpenChange={setRoleModalOpenState}
              size="large"
              width={500}
            >
              <ProFormText
                width="md"
                name="name"
                label="职位名称"
                tooltip="最长为 24 位"
                placeholder="请输入名称"
                initialValue={RoleMorA === "update" ? RoleUpdateMsg.name : ""}
                rules={[{ required: true,  validator: validateRoleName }]}
              />
              <ProFormText
                width="lg"
                name="description"
                label="描述"
                placeholder="描述一下岗位的作用:比如管理员具有最高权限"
                initialValue={
                  RoleMorA === "update" ? RoleUpdateMsg.description : ""
                }
                rules={[{ required: true,  validator: validateDescription }]}
              />
            </ModalForm>
          </div>
        </div>
      </Content>
    </div>
  );
};

export default App;
